//
//  HomeListTableView.swift
//  MT
//
//  Created by M on 2019/12/13.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit

import MTCategory
import JXPagingView
import ZFPlayer

class HomeListTableView: UITableView {
    
    /// 模型
    var models: [HomeListDetailModel]? {
        didSet {
            reloadData()
            guard let models = models else { return }
            if models.count > 0 {
                
            }
        }
    }
    
    var type: Int = 0 {
        didSet {
            
        }
    }
    
    /// 是否在播放
    fileprivate var isPlaying: Bool {
        return self.player.currentPlayerManager.isPlaying ?? false
    }
    /// 播放器
    lazy var player: ZFPlayerController = {
        let manager = ZFAVPlayerManager()
        manager.view.backgroundColor = MainBackgroundColor
        let p = ZFPlayerController(scrollView: self, playerManager: manager, containerViewTag: 8800)
        p.isWWANAutoPlay = true
        p.playerDisapperaPercent = 0.5
        p.allowOrentitaionRotation = false
        p.gestureControl.disableTypes = ZFPlayerDisableGestureTypes.all
        p.notification.willResignActive = { [weak self] (registrar) in
            guard let weakSelf = self else { return }
            if p.isViewControllerDisappear {
                return
            }
            if p.isFullScreen && p.isLockedScreen == false {
                p.orientationObserver.isLockedScreen = true
            }
            if p.pauseWhenAppResignActive == false {
                UIApplication.shared.beginReceivingRemoteControlEvents()
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
            }
        }
        return p
    }()
    
    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

// MARK: ------------------ Initialize ----------------------
extension HomeListTableView {
    
    private func setup() {
        backgroundColor = UIColor(hex:0x000000)
        separatorStyle = .none
        showsVerticalScrollIndicator = false
        isPagingEnabled = true
        bounces = false
        delegate = self
        dataSource = self
        alwaysBounceVertical = true
        scrollsToTop = false
        
        /// 注册 Cell
        register(HomeListMultipleCell.self, forCellReuseIdentifier: String(describing: HomeListMultipleCell.self))
        register(HomeListTableViewCell.self, forCellReuseIdentifier: String(describing: HomeListTableViewCell.self))
        
        /// 滑动回调
        self.zf_scrollViewDidStopScrollCallback = { [weak self] (indexPath) in
            guard let weakSelf = self else { return }
            if let iP = weakSelf.indexPathsForVisibleRows?.first {
                weakSelf.playVideo(at: iP, scrollToTop: false)
            }
        }
        /// 播放结束回调
        self.player.playerDidToEnd = { [weak self] (asset) in
            guard let weakSelf = self else { return }
            weakSelf.player.currentPlayerManager.replay?()
        }
    }
    
}

// MARK: ------------------ 播放器控制 ----------------------
extension HomeListTableView {
    
    /// 根据 IndexPath 播放内容
    public func playVideo(at indexPath: IndexPath, scrollToTop: Bool) {
        guard let model = models?[indexPath.row] else { return }
        if model.isContainVideo, let href = model.imgs?[1].href, let url = URL(string: href) {
            if self.player.playingIndexPath != indexPath {
                try? AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
                self.player.playTheIndexPath(indexPath, assetURL: url, scrollToTop: false)
            }
        } else {
            self.player.stopCurrentPlayingCell()
            try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
        }
        self.player.currentPlayerManager.view.isHidden = !model.isContainVideo
    }
    
    /// 播放
    public func play() {
        if isPlaying { return }
        self.player.currentPlayerManager.play?()
    }
    
    /// 暂停
    public func pause() {
        if !isPlaying { return }
        self.player.currentPlayerManager.pause?()
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UITableViewDelegate ----------------------
extension HomeListTableView: UITableViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidEndDecelerating()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        scrollView.zf_scrollViewDidEndDraggingWillDecelerate(decelerate)
    }
    
    func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScrollToTop()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewDidScroll()
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        scrollView.zf_scrollViewWillBeginDragging()
    }
        
}

// MARK: ------------------ UITableViewDataSource ----------------------
extension HomeListTableView: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if type == 0 {
            if models?.count == 1 {
                return models!.count + 1
            }
            let result = (models?.count ?? 0) % 2;
            if (result == 0) {
                return (models?.count ?? 0) / 2;
            }else if (result == 1){
                return (models?.count ?? 0) / 2 + 1;
            }
            return 0
        } else {
            return models?.count ?? 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if type == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: HomeListMultipleCell.self), for: indexPath) as? HomeListMultipleCell else {
                return tableView.dequeueReusableCell(withIdentifier: String(describing: HomeListMultipleCell.self), for: indexPath)
            }
            cell.coverImageViewLeft.tag = 2 * indexPath.row
            cell.coverImageViewRight.tag = 2 * indexPath.row + 1
            if models?.count == 1 {
                let model = models![0]
                cell.model = model
            }
            
            if (models?.count ?? 0) > 1 {
                let result  = models!.count % 2
                if result == 0 {
                    let model1 = models![indexPath.row * 2]
                    cell.model = model1
                    
                    let model2 = models![indexPath.row * 2 + 1]
                    cell.rightmodel = model2
                }
                
                if result == 1 {
                    let model1 = models![indexPath.row * 2]
                    cell.model = model1
                    let row = indexPath.row * 2 + 1
                    if (row <= (models!.count-1)) {
                        let model2 = models![indexPath.row*2+1]
                        cell.rightmodel = model2
                    } else if (indexPath.row*2+1 == models!.count) {
                        
                    }
                }
            }
            //        cell.delegate = self
            //        cell.model = models?[indexPath.row]
            return cell
        } else {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: HomeListTableViewCell.self), for: indexPath) as? HomeListTableViewCell else {
                return tableView.dequeueReusableCell(withIdentifier: String(describing: HomeListTableViewCell.self), for: indexPath)
            }
            cell.delegate = self
            cell.model = models?[indexPath.row]
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if type == 0 {
            return 250
        } else {
            return ScreenHeight
        }
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

// MARK: ------------------ HomeListTableViewCellDelegate ----------------------
extension HomeListTableView: HomeListTableViewCellDelegate {
    
    func homeListCellDidClickPlayPauseButton(_ cell: HomeListTableViewCell, isPlay: Bool) {
        isPlay ? self.play() : self.pause()
    }
    
}
